const util = require('../util/util')
const Sequelize = require('sequelize')
const SequelizeModel = require('./SequelizeModel')
const errorConst = require('../const/error')
const commonConst = require('../const/common')

let User = SequelizeModel.define('nm_user', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: Sequelize.STRING,
  password: Sequelize.STRING,
  nickname: Sequelize.STRING,
  created_at: Sequelize.INTEGER,
  salt: Sequelize.STRING,
  status: Sequelize.INTEGER
}, {
  tableName: 'nm_user',
  timestamps: false,
  freezeTableName: true
})

const exModel = {
  createByData: async data => {
    let retFlag = false
    if (!data.name || !data.nickname || !data.password) {
      throw new Error(errorConst.userAddNeedInfo)
    }
    let userModel = User
    let salt = util.randomString(8)
    let password = util.passwordMd5(data.password, salt)
    let result = await userModel.create({
      name: data.name,
      password: password,
      nickname: data.nickname,
      created_at: util.nowTime(),
      salt: salt,
      status: commonConst.statusCommon
    })
    console.log(result)

    if (result) {
      retFlag = true
    }
    return retFlag
  },
  checkUser: async function (username, password) {
    let retInfo = false
    let user = await User.findOne({
      where: {name: username}
    })

    if (user) {
      let salt = user.salt
      let passwordFromData = user.password

      if (util.passwordMd5(password, salt) === passwordFromData) {
        retInfo = {id: user.id, name: user.name, nickname: user.nickname}
      }
    }
    return retInfo
  },
  checkUserIsExist: async function (username) {
    let retFlag = false

    let user = await User.findOne({
      where: {name: username}
    })
    if (user) {
      retFlag = true
    }
    return retFlag
  }
}

module.exports = exModel
